package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
	"net/http"
	"strconv"
	"test/common"
	"test/dto"
	"test/model"
	"test/util"
)

func Manger_Register(ctx *gin.Context) {
	DB := common.GetDB()
	//获取参数
	Manger_num :=ctx.PostForm("Manger_num")
	Manger_password :=ctx.PostForm("password")
	//数据验证
	//if len(snostring) < 5{
	//	ctx.JSON(http.StatusUnprocessableEntity,gin.H{"code":422,"msg":"学号编号必须为10位"})
	//	return
	//}
	//if len(spassword) < 6 {
	//	ctx.JSON(http.StatusUnprocessableEntity,gin.H{"code":422,"msg":"密码不能少于6位"})
	//	return
	//}
	sno,err:=strconv.Atoi(snostring)
	if err != nil {
		fmt.Println("不存在!")
	}
	//如果名称没有传，
	if len(sname) == 0 {
		sname = util.RandomString(10)
		return
	}
	//判断学号是否存在
	if isSnoExists(DB,sno) {
		ctx.JSON(http.StatusUnprocessableEntity,gin.H{"code":422,"msg":"学生已经存在"})
		fmt.Println("我执行了")
		return
	}
	//创建用户
	//hasedPassword,err := bcrypt.GenerateFromPassword([]byte(spassword),bcrypt.DefaultCost)//密码加密
	//if err != nil {
	//	fmt.Println("我执行了")
	//}
	newStudent := model.Students{
		Sno:      sno,
		Sname:    sname,
		Sdate: 	  sdate,
		Spayment: spayment,
		Spassword: spassword,
	}
	DB.Create(&newStudent)
	//返回结果
	ctx.JSON(200, gin.H{
		"code" : 200,
		"msg": "注册成功",
	})
}

func Manger_Login(ctx *gin.Context) {
	//获取参数
	db := common.GetDB()
	sno:=ctx.PostForm("sno")
	password:=ctx.PostForm("password")
	//数据验证
	//if len(sno) != 2 {
	//	ctx.JSON(http.StatusUnprocessableEntity,gin.H{"code":422,"msg":"学号必须为11号"})
	//	return
	//}
	//if len(password) < 6 {
	//	ctx.JSON(http.StatusUnprocessableEntity,gin.H{"code":422,"msg":"密码不能少于6位"})
	//	return
	//}
	//判断学号是否存在
	var student model.Students
	db.Where("sno = ?",sno).First(&student)
	if student.Sno == 0 {
		ctx.JSON(http.StatusUnprocessableEntity,gin.H{"code":422,"msg":"用户不存在！"})
	}
	//判断密码是否正确
	if err := bcrypt.CompareHashAndPassword([]byte(student.Spassword), []byte(password)) ; err != nil {
		ctx.JSON(http.StatusUnprocessableEntity,gin.H{"code":422,"msg":"密码错误！"})
		return
	}
	//发放token
	//token , err:= common.ReleseToken(student)
	//if err != nil {
	//	ctx.JSON(http.StatusInternalServerError, gin.H{"code":500,"msg":"系统错误"})
	//	log.Printf("token generate error : %v",err)
	//	return
	//}
	//返回结果
	ctx.JSON(200, gin.H{
		"code": 200,
		"msg": "登录成功",
	})
}
func Manger_Info(ctx *gin.Context) {
	user,_:= ctx.Get("people")
	ctx.JSON(http.StatusOK,gin.H{"code":200,"data":gin.H{"people":dto.ToUserDto(user.(model.Students))}})
}

func Manger_isSnoExists(db *gorm.DB,sno int) bool {//string
	var people model.Students
	db.Where("sno = ?",sno).First(&people)
	fmt.Println(people)
	if people.Sno != 0 {
		return true
	} else {
		return false
	}
}

